package com.atguigu.util;

import com.atguigu.common.Constant;
import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.async.RedisAsyncCommands;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisUtil {

    private static JedisPool jedisPool;

    static {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(100);
        poolConfig.setMaxIdle(5);
        poolConfig.setMinIdle(5);
        poolConfig.setBlockWhenExhausted(true);
        poolConfig.setMaxWaitMillis(2000);
        poolConfig.setTestOnBorrow(true);

        jedisPool = new JedisPool(poolConfig, "hadoop102", 6379, 10000);
    }

    public static JedisPool getJedisPool() {
        return jedisPool;
    }

    public static Jedis getJedis() {
        System.out.println("~~~获取Jedis客户端~~~");
        return jedisPool.getResource();
    }


    public static void deleteData(Jedis jedis, String tableName, String pk) {
        String redisKey = "DIM:" + tableName + ":" + pk;
        jedis.del(redisKey);
    }

    public static void setData(Jedis jedis, String tableName, String pk, String value) {
        String redisKey = "DIM:" + tableName + ":" + pk;
        jedis.setex(redisKey, Constant.ONE_DAY, value);
    }

    /**
     * 获取一个到 redis 线程安全的异步连接, key value 都用 utf-8 进行编码
     *
     * @return
     */
    public static StatefulRedisConnection<String, String> getAsyncRedisConnection() {
        // 连接到 redis
        RedisClient redisClient = RedisClient.create("redis://hadoop102:6379");
        return redisClient.connect();
    }

    public static void setDataByAsync(StatefulRedisConnection<String, String> redisConnection, String tableName, String pk, String value) {
        String redisKey = "DIM:" + tableName + ":" + pk;
        RedisAsyncCommands<String, String> async = redisConnection.async();
        async.setex(redisKey, Constant.ONE_DAY, value);
    }

    public static void main(String[] args) {
        Jedis jedis = getJedis();
        String pong = jedis.ping();
        System.out.println(pong);

        jedis.close();
    }
}
